<script setup lang="ts">
import { ref } from 'vue'
import { userLogin } from '../../api/user'
import { useTokenStore } from "../../store/tokenStore"
import { useUserStore } from '../../store/userStore'
import { useRouter } from 'vue-router'
import { ElMessage } from "element-plus"
import { HttpStatusCode } from "axios"
import config from '../../config'

const router = useRouter()
const tokenStore = useTokenStore()
const userStore = useUserStore()

const userName = ref<string>('')
const password = ref<string>('')
const load = ref<boolean>(false)

const login = async () => {
  load.value = true
  const data = {
    userName: userName.value,
    password: password.value
  }
  const res = await userLogin(data)
  if(res.statusCode === HttpStatusCode.Created) {
    const { token, user } = res.data as any

    tokenStore.$patch({token})
    userStore.$patch({user})

    load.value = false
    ElMessage({
      type: 'success',
      message: '登录成功'
    })
    await router.push({path: '/'})
  } else {
    load.value = false
    ElMessage({
      type: 'error',
      message: '登录失败'
    })
  }

}
</script>

<template>
  <div class="container">
    <h2 class="bigTitle">{{config.adminTitle}} V{{config.version}}</h2>
    <div class="box">
      <div class="form">
        <span class="title">登录</span>
        <el-input class="inp" v-model="userName" placeholder="用户名" />
        <el-input class="inp" v-model="password"
          type="password"
          show-password
          placeholder="密码" />
        <el-button class="btn" color="#6666FF" :loading="load" @click="login">登录</el-button>
      </div>
    </div>
  </div>
</template>

<style lang="less" scoped>
.container {
  width: 100vw;
  height: 100vh;
  background-color: @GlobalColor;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  .bigTitle {
    margin-bottom: 20px;
    color: #fff;
  }
  .box {
    width: 500px;
    height: 300px;
    background-color: #fff;
    border-radius: 6px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    .form {
      width: 300px;
      height: 200px;
      //border: 1px solid #000;
      display: flex;
      flex-direction: column;
      align-items: center;
      //justify-content: center;
      .inp {
        width: 270px;
        margin: 10px;
      }
      .title {
        font-size: 22px;
      }
      .btn {
        width: 150px;
        height: 40px;
        margin-top: 10px;
      }
    }

  }
}
</style>
